﻿using System;
using System.Net;
using HttpServer.HttpModules;
using HttpServer.MVC;
using HttpServer.MVC.Rendering.Spark;
using Spark;
using SparkServer.Controllers;

namespace SparkServer
{
    /// <summary>
    /// The WebServer setup class. 
    /// Uses an internal instance of the C# WebServer.
    /// </summary>
    class WebServer
    {
        private static HttpServer.HttpServer _Server;

        // TODO: Move this to configuration. DTHRASHER 13Oct2009
        private static readonly IPAddress Address = IPAddress.Any;
        private const int Port = 8081;

        /// <summary>
        /// Initializes and starts the web server.
        /// </summary>
        public static void Start()
        {
            // Initialize the Spark container. 
            // This will be used in all SparkControllers.
            SparkSettings settings = new SparkSettings
                                         {
                                             Debug = true,
                                             AutomaticEncoding = true,
                                             PageBaseType = typeof(SparkView).FullName
                                         };

            SparkServiceContainer container = new SparkServiceContainer(settings);

            // Create an instance of the C# WebServer.
            _Server = new HttpServer.HttpServer();


            // Supply custom modules here. These do not use the Spark View Engine.
            _Server.Add(new StatusModule());


            // Add Spark controllers for pages that use Spark templates.
            ControllerModule mod = new ControllerModule();
            mod.Add(new HomeController(container));
            _Server.Add(mod);


            // Plain old file modules.
            // The file module simply sends files to the browser (if they are found).

            FileModule fhImages = new FileModule("/image", Environment.CurrentDirectory + "\\content\\image\\");
            fhImages.AddDefaultMimeTypes();
            _Server.Add(fhImages);

            FileModule fhStyle = new FileModule("/style", Environment.CurrentDirectory + "\\content\\style\\");
            fhStyle.AddDefaultMimeTypes();
            _Server.Add(fhStyle);

            FileModule fhScript = new FileModule("/script", Environment.CurrentDirectory + "\\script\\");
            fhScript.AddDefaultMimeTypes();
            _Server.Add(fhScript);


            // Configuration complete. Start the server.
            _Server.Start(Address, Port);
        }

        /// <summary>
        /// Shuts down the web server.
        /// </summary>
        public static void Stop()
        {
            _Server.Stop();
        }
    }
}